package com.authority.controller;

import com.authority.common.AdminConstants;
import com.authority.common.AuthConstants;
import com.authority.entry.AuthRoleDO;
import com.authority.entry.AuthRoleMenuDO;
import com.authority.entry.AuthSysDO;
import com.authority.query.AuthRoleQuery;
import com.authority.service.AuthMenuService;
import com.authority.service.AuthRoleService;
import com.authority.service.AuthRoleTypeService;
import com.authority.service.AuthSysService;
import com.authority.tree.Node;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.suixun.util.Constant;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 角色管理
 * @author limeng.g
 *
 */

@Controller
@RequestMapping(value = "/roleManager")
public class RoleManager extends BaseManager {
	@Resource
	private AuthRoleService authRoleService;
	
	@Resource
	private AuthRoleTypeService authRoleTypeService;
	
	@Resource
	private AuthSysService authSysService;
	@Resource
	private AuthMenuService authMenuService;

	/**
	 * 角色列表查询
	 * @param name 名称
	 * @param code 编码
	 * @param type 角色类型
	 * @param sysId 所属系统
	 * @param index 页码
	 * @return
	 */
	
	@RequestMapping(value = "/listRole.json")
	@ResponseBody
	public Object doListRoleByPaging(String param) {
		if (param == null)
			param = "";
		try {
			AuthRoleQuery query = new Gson().fromJson(param, AuthRoleQuery.class);
			if(query==null) {
				query=new AuthRoleQuery();
			}
			query.setIsDownload(true);
			if(query.getSysId()==null) {
				AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
				if(null!=sys){
					query.setSysId(sys.getId());
				}
			}
			return success(authRoleService.listAuthRole(query));
		} catch (Exception e) {
			logger("RoleManager doListRole:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	
	@RequestMapping(value = "/getUserRoles.json")
	@ResponseBody
	public Object getUserRoles(String param) {
		
		try {
			AuthRoleQuery query = checkParam(param, AuthRoleQuery.class);
			if(query.getSysId()==null) {
				AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
				if(null!=sys){
					query.setSysId(sys.getId());
				}
			}
			return success(authRoleService.getRoleList(query));
		} catch (Exception e) {
			logger("RoleManager getUserRoles:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}

	/**
	 * 添加角色
	 * @param name 名称
	 * @param code 编码
	 * @param type 角色类型
	 * @param sysId 所属类型
	 * @param remark 备注
	 * @param nodes 权限列表
	 * @return
	 */
	
	@RequestMapping(value = "/saveRole.json")
	@ResponseBody
	public Object doSaveRole(String param) {
		try {
			if (param == null)
				param = "";
			AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
			AuthRoleDO db = new Gson().fromJson(param, AuthRoleDO.class);
			db.setSysId(sys.getId());
			checkParams(db.getName(),db.getCode());
			db.setOperatorId(getUserId());
			
			List<AuthRoleMenuDO> list = Lists.newArrayList();
			String nodes=db.getNodes();
			if(StringUtils.isNotEmpty(nodes)){
				nodes=nodes.replaceAll("\\|", ",");
				Map<String,String> map = generateMap(nodes);
				for(String key : map.keySet()){
					AuthRoleMenuDO rmdb = new AuthRoleMenuDO();
					rmdb.setMenuId(NumberUtils.toLong(key));
					rmdb.setActionIds(map.get(key));
					rmdb.setOperatorId(getUserId());
					rmdb.setSysId(db.getSysId());
					list.add(rmdb);
				}
			}
			
			authRoleService.saveAuthRole(db, list);
			
			return success(AdminConstants.CODE_STATUS_SUCCESS);
		} catch (Exception e) {
			logger("RoleManager doSaveRole:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 把权限字符串转换成map
	 * @param nodes  形如1,2,3,3_1,3_2
	 * @return 
	 */
	private Map<String,String> generateMap(String nodes){
		Map<String,String> map = Maps.newHashMap();
		for(String p : nodes.split(AuthConstants.SEPARATOR_COMMA)){
			if(Pattern.compile("^[0-9]{1,}_[0-9]{1,}$").matcher(p).matches()){
				String menuId = p.split("_")[0];
				String actionId = p.split("_")[1];
				if(map.containsKey(menuId) && map.get(menuId) !=null){
					map.put(menuId, map.get(menuId) + AuthConstants.SEPARATOR_COMMA + actionId);
				}else{
					map.put(menuId, actionId);
				}
			}else{
				if(!map.containsKey(p)){
					map.put(p, null);
				}
			}
		}
		
		return map;
	}
	
	/**
	 * 获取未选择的菜单树(菜单+功能)
	 * @param sysId
	 * @return
	 */
	@RequestMapping(value = "/treeUncheckedMenu.json")
	@ResponseBody
	public Object  doTreeUncheckedMenu( Long sysId){
		
		try {
			checkParams(sysId);
			return success(authRoleService.treeUncheckedMenu(sysId));
		} catch (Exception e) {
			logger("RoleManager doTreeUncheckedMenu:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	@RequestMapping(value = "/noCheck_treeUncheckedMenu.json")
	@ResponseBody
	public Object  getTreeUncheckedMenu(){
		AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
		return doTreeUncheckedMenu(sys.getId());
	}
	
	@RequestMapping(value = "/getMenu.json")
	@ResponseBody
	public Object  getMenu(){
		AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
		return success(authMenuService.listAuthMenuBySysId(sys.getId()));
	}
	
	/**
	 * 获取已选择的菜单树(菜单+功能)
	 * @param sysId
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/treeCheckedMenu.json")
	@ResponseBody
	public Object  doTreeCheckedMenu(Long sysId,Long roleId){
		
		try {
			checkParams(sysId,roleId);
			
			Node node = authRoleService.treeCheckedMenu(roleId,sysId);
			
			return success(node);
		} catch (Exception e) {
			logger("RoleManager doTreeCheckedMenu:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	@RequestMapping(value = "/getCheckedMenu.json")
	@ResponseBody
	public Object  getCheckedMenu(String param){
		if (param == null)
			param = "";
		AuthRoleDO dbtemp = new Gson().fromJson(param, AuthRoleDO.class);
		AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
		return success(authRoleService.listAuthMenuByRoleIdAndSysId(dbtemp.getId(),sys.getId()));
	}
	
	/**
	 * 更新角色
	 * @param id 角色id
	 * @param name 名称
	 * @param code 编码
	 * @param type 角色类型
	 * @param sysId 所属系统
	 * @param remark 备注
	 * @param nodes 权限列表
	 * @return
	 */
	@RequestMapping(value = "/updateRole.json")
	@ResponseBody
	public Object doUpdateRole(String param) {
		if (param == null)
			param = "";
		AuthRoleDO dbtemp = new Gson().fromJson(param, AuthRoleDO.class);
		try {
			AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
			dbtemp.setSysId(sys.getId());
			checkParams(dbtemp.getId(),dbtemp.getName(),dbtemp.getCode(),dbtemp.getType());

			AuthRoleDO db = authRoleService.getAuthRoleById(dbtemp.getId());
			db.setName(dbtemp.getName());
			db.setCode(dbtemp.getCode());
			db.setType(dbtemp.getType());
			db.setSysId(dbtemp.getSysId());
			db.setRemark(dbtemp.getRemark());
			db.setOperatorId(getUserId());
			
			List<AuthRoleMenuDO> list = Lists.newArrayList();
			String nodes=dbtemp.getNodes();
			if(StringUtils.isNotEmpty(nodes)){
				nodes=nodes.replaceAll("\\|", ",");
				Map<String,String> map = generateMap(nodes);
				for(String key : map.keySet()){
					AuthRoleMenuDO rmdb = new AuthRoleMenuDO();
					rmdb.setRoleId(db.getId());
					rmdb.setMenuId(NumberUtils.toLong(key));
					rmdb.setActionIds(map.get(key));
					rmdb.setOperatorId(getUserId());
					rmdb.setSysId(dbtemp.getSysId());
					list.add(rmdb);
				}
			}
			
			authRoleService.updateAuthRole(db, list);
			
			return success(AdminConstants.CODE_STATUS_SUCCESS);
		} catch (Exception e) {
			logger("RoleManager doUpdateRole:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 获取角色信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getRoleById.json")
	@ResponseBody
	public Object doGetRoleById(Long id){
		try {
			checkParams(id);
			
			return success(authRoleService.getAuthRoleById(id));
		} catch (Exception e) {
			logger("RoleManager doGetRoleById:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 获取角色列表(id,name)
	 * @param sysId
	 * @return
	 */
	@RequestMapping(value = "/listRoleIdName.json")
	@ResponseBody
	public Object doListRoleIdName(Long sysId){
		try {
			checkParams(sysId);
			
			return success(authRoleService.listAuthRoleIdName(sysId));
		} catch (Exception e) {
			logger("RoleManager doListRoleIdName:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 获取角色类型列表(id,name)
	 * @param sysId
	 * @return
	 */
	@RequestMapping(value = "/listRoleTypeIdName.json")
	@ResponseBody
	public Object doListRoleTypeIdName(Long sysId){
		try {
			checkParams(sysId);
			
			return success(authRoleTypeService.listRoleTypeIdName(sysId));
		} catch (Exception e) {
			logger("RoleManager doListRoleTypeIdName:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	@RequestMapping(value = "/listRoleTypeByIdName.json")
	@ResponseBody
	public Object getlistRoleTypeIdName(String param){
		if (param == null)
			param = "";
		try {
			AuthSysDO sys = authSysService.queryAuthSysByCode(AdminConstants.SYSTEM_CODE);
			
			return success(authRoleTypeService.listRoleTypeIdName(sys.getId()));
		} catch (Exception e) {
			logger("RoleManager getlistRoleTypeIdName:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 获取按角色类型分组的角色列表
	 * @param sysId
	 * @return
	 */
	@RequestMapping(value = "/listAuthRoleGroupByType.json")
	@ResponseBody
	public Object doListAuthRoleGroupByType(Long sysId) {

		try {
			checkParams(sysId);
			
			return success(authRoleService.listAuthRoleGroupByType(sysId));
		} catch (Exception e) {
			logger("RoleManager doListAuthRoleGroupByType:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
}
